package com.wangjiawei.dao.imp;

import com.wangjiawei.dao.BaseAdminDao;
import com.wangjiawei.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/2 9:26
 * 4
 */
public class AdminDaoMysql implements BaseAdminDao {
    private static final String SQL_UPDATE_LOGIN_TIME = "UPDATE EADMIN SET LOGINTIME = ?, LOGINIP = ? WHERE USERNAME = ?";
    private static final String SQL_LOGIN = "SELECT ID FROM EADMIN WHERE USERNAME = ? AND PASSWORD = ?";

    /**
     * 根据用户名，更新登录时间和登录ip
     *
     * @param username
     * @param date
     * @param ip
     */
    @Override
    public void updateLoginTime(String username, Date date, String ip) {
        Connection connection = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = connection.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            state.setDate(1, new java.sql.Date(date.getTime()));
            state.setString(2, ip);
            state.setString(3, username);
            state.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(connection,state,null);
        }
    }

    /**
     * 管理员根据账号密码登录
     *
     * @param username
     * @param password
     * @return 登录结果 true：登录成功
     */
    @Override
    public boolean login(String username, String password) {
        Connection connection = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet resultSet = null;
        try {
            state = connection.prepareStatement(SQL_LOGIN);
            state.setString(1,username);
            state.setString(2,password);
            resultSet = state.executeQuery();
            // 如果能查出来则有，返回true
            return resultSet.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(connection,state,null);
        }
        return false;
    }
}
